package com.moco.launcher.download;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.moco.launcher.play.MusicItemInfo;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.View;

public class MocoDownloadManager {
	private static final String TAG = "MocoDownloadManager";

	private volatile static MocoDownloadManager instance;
	private static DownloadManager mDownloadManager = null;
	private static Context mCtx = null;

	/** Returns singleton class instance */
	public static MocoDownloadManager getInstance() {
		if (instance == null) {
			synchronized (MocoDownloadManager.class) {
				if (instance == null) {
					instance = new MocoDownloadManager();
				}
			}
		}
		return instance;
	}

	public void init(Context context) {
		mCtx = context;
		mDownloadManager = (DownloadManager) mCtx
				.getSystemService(mCtx.DOWNLOAD_SERVICE);
		mCtx.registerReceiver(receiver, new IntentFilter(
				DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	}

	private static final String EXTERNAL_DIR = "mocodownload";

	private boolean isFolderExist(String dir) {
		File folder = Environment.getExternalStoragePublicDirectory(dir);
		return (folder.exists() && folder.isDirectory()) ? true : folder
				.mkdirs();
	}

	public void startDownload(MusicItemInfo info) {
		if (mDownloadManager != null) {
			String ext = ".mp3";
			String savename = info.getId() + info.getTitle() + ext;
			Log.d(TAG, "DOWNLOAD url=" + info.getUrl());
			Log.d(TAG, "DOWNLOAD ext=" + ext);
			Log.d(TAG, "DOWNLOAD savename=" + savename);
			Request request = new Request(Uri.parse(info.getUrl()));
			request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
			request.setTitle(info.getTitle());
			request.setDescription(info.getDesc());
			isFolderExist(EXTERNAL_DIR);
			request.setDestinationInExternalPublicDir(EXTERNAL_DIR, savename);
			request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
			long id = mDownloadManager.enqueue(request);
			Log.d(TAG, "ID = " + id);
		}
	}

	public void removeDownload(MusicItemInfo info) {
		DownloadManager.Query query = new DownloadManager.Query();
		Cursor c = mDownloadManager.query(query);

		while (c.moveToFirst()) {
			String title = c.getString(c
					.getColumnIndex(DownloadManager.COLUMN_TITLE));
			int id = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_ID));
			if (title.contains(info.getTitle())) {
				mDownloadManager.remove(id);
				break;
			}
		}
	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 这里可以取得下载的id，这样就可以知道哪个文件下载完成了适用与多个下载任务的监听
			Log.v(TAG,
					""
							+ intent.getLongExtra(
									DownloadManager.EXTRA_DOWNLOAD_ID, 0));
			queryDownloadStatus();
		}
	};

	private String encodeGB(String string) {
		String split[] = string.split("/");
		for (int i = 1; i < split.length; i++) {
			try {
				split[i] = URLEncoder.encode(split[i], "GB2312");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			split[0] = split[0] + "/" + split[i];
		}
		split[0] = split[0].replaceAll("\\+", "%20");// 处理空格
		return split[0];
	}

	private void queryDownloadStatus() {
		DownloadManager.Query query = new DownloadManager.Query();
		query.setFilterByStatus(DownloadManager.STATUS_PENDING
				| DownloadManager.STATUS_PAUSED);
		Cursor c = mDownloadManager.query(query);
		if (c.moveToFirst()) {
			int status = c.getInt(c
					.getColumnIndex(DownloadManager.COLUMN_STATUS));
			switch (status) {
			case DownloadManager.STATUS_PAUSED:
				Log.v("down", "STATUS_PAUSED");
			case DownloadManager.STATUS_PENDING:
				Log.v("down", "STATUS_PENDING");
			case DownloadManager.STATUS_RUNNING:
				// 正在下载，不做任何事情
				Log.v("down", "STATUS_RUNNING");
				break;
			case DownloadManager.STATUS_SUCCESSFUL:
				// 完成
				Log.v("down", "下载完成");
				break;
			case DownloadManager.STATUS_FAILED:
				// 清除已下载的内容，重新下载
				Log.v("down", "STATUS_FAILED");
				break;
			}
		}
	}
}
